package com.og.vas.linstener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.og.vas.mapper.UserInfoMapper;
import com.og.vas.pojo.dto.ExcelUserDTO;

import java.util.ArrayList;
import java.util.List;

//excel文件读取监听器
public class ExcelUserListener extends AnalysisEventListener<ExcelUserDTO> {



    //构造器注入属性
    public ExcelUserListener(UserInfoMapper mapper){
        this.mapper = mapper;
    }

    private final UserInfoMapper mapper;


    //数据列表
    List<ExcelUserDTO> list= new ArrayList<>();

    //数据列表最大值
    private static final int BATCH_COUNT = 5;



    //每解析一条数据执行invoke
    @Override
    public void invoke(ExcelUserDTO data, AnalysisContext context) {

        list.add(data);
        System.out.println(data);


        //将数据表存入数据库
        if (list.size() >= BATCH_COUNT){
            SaveData();
            list.clear();
        }
    }


    //解析完所有数据
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //当最后剩余数据不足BATCH_COUNT,一次性存储所有数据
        SaveData();
        list.clear();
    }

    private void SaveData(){
        //底层调用保存
        mapper.insertBatch(list);
    }
}
